package org.jiajie.effective.concurrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池丢弃策略
 *
 * @author jay
 */
public class AbortTest {
    // 线程数量
    private static final int THREAD_COUNT = 50;
    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(THREAD_COUNT);
    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(1);

    /**
     * 线程池丢弃策略
     *
     * @param args  参数
     */
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(20),
                new ThreadPoolExecutor.AbortPolicy());
        // DiscardPolicy 丢弃
        // AbortPolicy 丢弃报错
        // DiscardOldestPolicy 将队列队首的任务丢弃，执行当前线程任务
        // CallerRunsPolicy 直接调用run方法
        // 提交线程
        for (int i = 0; i < THREAD_COUNT; i++) {
            threadPoolExecutor.execute(() -> {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "execute!" + ATOMIC_INTEGER.getAndIncrement());
                COUNT_DOWN_LATCH.countDown();
            });
        }
        COUNT_DOWN_LATCH.await();
        // 关闭线程
        threadPoolExecutor.shutdown();
    }
}
